import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
declare var $: any;
@Component({
	selector: 'sa-device-status',
	templateUrl: './device-status.component.html',
	styleUrls: ['./device-status.component.css']
})
export class DeviceStatusComponent implements OnInit {
	tableData: any[] = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword
	selectedCompanyName: string = ''; 公司名称
	selectedCompanyId: string = '';//公司ID
	deviceId: string = '';
	useTypeL1: string = '';//useTypeL1  select值
	useTypeL2: string = '';//useTypeL2  select值
	sensorType: string = '';//传感器类型参数
	carTypeDetailList: any = [];//useTypeL2数据
	allChecked: boolean = false;//table全选状态值
	runStatus: boolean = true; //存储设备在线状态
	selectedRow = false;//记录是否选择了row/
	sortType: string = '';//排序
	online: string = '0'; //是否在线  1.在线  2.离线 默认全部0
	state: string = '0'; //到期状态  1.未到期 2.已到期 默认全部0
	isShowDeviceDetail: any = false; // 默认不显示设备详情
	isShowParameter: boolean = false; //默认不显示参数配置
	isShowExport: boolean = false; //默认不显示导出
	isShowFirmwareInfo: boolean = false; //详情-固件信息
	isShowAlarmInfo: boolean = false; //详情-警报信息
	isShowDataInfo: boolean = false; //详情-数据信息
	isShowRepairInfo: boolean = false; //详情-维修信息
	isShowDeviceInfo: boolean = false; //详情-设备信息
	selected: any;
	carTypeList = carTypeListObj.carTypeList
	carUseList = carTypeListObj.carUseList
	carDeatailUseList = carTypeListObj.carDeatailUseList
	startTime: string = '';
	endTime: string = '';
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}
	//公司选中回调
	companySelected(data) {
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}
	ngOnInit() {
		this.initBtn();
		this.load();
	}
	ngOnDestroy() {
		document.onclick = null;
	}
	// 初始化按钮
	initBtn() {
		var btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_car:device:status')));
		if (!btnData) {
			return
		};
		for (let item of btnData) {
			if (item.sourceKey === "car:device:detailBtn" && item.parentId) {
				this.isShowDeviceDetail = true;
			}
			if (item.sourceKey === "car:device:parameterBtn" && item.parentId) {
				this.isShowParameter = true;
			}
			if (item.sourceKey === "car:device:exportBtn" && item.parentId) {
				this.isShowExport = true;
			}
			if (item.sourceKey === "device:status:firmwareInfo" && item.parentId) {
				this.isShowFirmwareInfo = true; //详情-固件信息
			}
			if (item.sourceKey === "device:status:alarmInfo" && item.parentId) {
				this.isShowAlarmInfo = true; //详情-警报信息
			}
			if (item.sourceKey === "device:status:dataInfo" && item.parentId) {
				this.isShowDataInfo = true; //详情-数据信息
			}
			if (item.sourceKey === "device:status:repairInfo" && item.parentId) {
				this.isShowRepairInfo = true; //详情-维修信息
			}
			if (item.sourceKey === "device:status:deviceInfo" && item.parentId) {
				this.isShowDeviceInfo = true; //详情-设备信息
			}
		}
	}
	//table刷新
	refresh() {
		this.load();
	}
	//表格搜索
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//初始化加载list数据
	load() {
		this.allChecked = false;
		this.selected = [];
		this.runStatus = true;
		let tableSearch = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				searchKey: this.searchKey,
				company: this.selectedCompanyId,
				online: this.online,
				state: this.state,
				sort: this.sortType,
				useTypeL2: $('#TcarTypeSelect2').val(),
				useTypeL1: $('#TcarTypeSelect2').val().slice(0, 2)
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(tableSearch);
		this.jsonApiService.http("system/realTimeDataByAuth.html", reqdata).subscribe(data => {
			if (data.exhibitDatas) {
				for (let item of data.exhibitDatas) {
					let carUploadDate = item.carUploadDate;
					let gpsUploadDate = item.gpsUploadDate;
					if (carUploadDate && gpsUploadDate) {
						let abs = Math.abs(common.mmsstoTimestamp(carUploadDate) - common.mmsstoTimestamp(gpsUploadDate));
						abs >= 30 * 60 * 1000 ? item.isShowGPSAlert = true : item.isShowGPSAlert = false;//计算GPS是否异常:更新时间 - gps更新时间  > 30分钟    =>GPS异常
					}
					item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);//车辆类型转换为中文
					item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);//车辆类型转换为中文
					item['isChecked'] = false;
					//计算到期时间是否到期
					item.isExpire = false
					let nowTime = new Date().getTime();
					if (item.renewalDueTime) {
						let time = (common.mmsstoTimestamp(item.renewalDueTime) - nowTime);
						if (time < 0) {
							item.isExpire = true //时间已到期
						}
					}

					if (item.coef) {
						let coefArr = [];
						for (let i = 0; i < item.coef.length; i++) {
							let _item = item.coef[i];
							if (_item) {
								var obj = {
									value: item.coef[i],
									index: i + 1
								}
								coefArr.push(obj);
							}
						}
						item.coef = coefArr;
					} else {
						item.coef = [];
					}
				}
			}
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	getUseTypeNameL1(key) {
		if (key) {
			return this.carUseList[key];
		} else {
			return '';
		}
	}
	getUseTypeNameL2(key) {
		if (key) {
			return this.carDeatailUseList[key];
		} else {
			return '';
		}
	}

	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//排序change事件
	sortChange() {
		this.load();
	}
	//是否在线
	// isOnline(val) {
	// 	if (val) {
	// 		this.online = "1";
	// 	} else {
	// 		this.online = "0";
	// 	}
	// 	this.load();
	// }
	//table 全部选中
	allSelected() {
		this.allChecked = !this.allChecked;
		if (!this.allChecked) {
			for (let item of this.tableData) {
				item['isChecked'] = false;
			}
			this.selected = [];
			this.deviceId = '';
		} else {
			var temArr = [];
			for (let item of this.tableData) {
				item['isChecked'] = true;
				temArr.push(item.deviceId);
				this.selected.push(item);
			}
			for (let item of this.selected) {
				temArr.push(item.deviceId);
				if (item.runStatus === '0') {
					this.runStatus = false;
				}
			}
			this.deviceId = temArr.join(',');
		}
	}
	//table复选框数据row选中事件回调:处理选中状态和deviceId
	rowSelected(row, e, index) {
		var index = $.inArray(row, this.selected);
		if (index === -1) {
			row.isChecked = true;
			this.selected.push(row);
		} else {
			row.isChecked = false;
			this.selected.splice(index, 1);
		}
		var temArr = [];
		for (let item of this.selected) {
			temArr.push(item.deviceId);
			if (item.runStatus === '0') { //判断选中数据中是否存在离线车辆
				this.runStatus = false;
			}
		}
		this.deviceId = temArr.join(','); //处理deviceId,与后台接口交互参数
		this.selected.length === this.pageSize ? this.allChecked = true : this.allChecked = false; //判断是否全选状态
	}
	/**
	 * 单行数据选中事件,仅支持单行选中,不支持多选
	 */
	singleRowSelected(row, e, index) {
		if (e.target.className.includes('checkbox') || e.target.className.includes('checkbox-flag') || e.target.className.includes('checkbox-td') || e.target.className.includes('checkbox-label')) {
			this.rowSelected(row, e, index);
			return;
		}
		for (let item of this.tableData) {
			item['isChecked'] = false;
		}
		this.selected = [];
		this.runStatus = true;
		row.isChecked = !row.isChecked;
		this.selected.push(row);
		if (row.runStatus === '0') {
			this.runStatus = false;
		}
		this.deviceId = row.deviceId;
	}
	//验证是否选择了数据
	checkSelected(type) {
		if (this.selected.length == 0) {
			this.jsonApiService.message('请选择需要' + type + '的数据');
			this.selectedRow = false;
			return;
		} else {
			this.selectedRow = true;
		}
	}
	//验证是否选择了数据(单行数据)
	checkSelectedRow(val) {
		if (this.selected.length == 0) {
			this.selectedRow = false;
			this.jsonApiService.message(val);
			return;
		} else {
			if (this.selected.length == 1) {
				this.selectedRow = true;
			} else {
				this.jsonApiService.message('你选择多条数据,请选择单行数据操作');
				this.selectedRow = false;
				return;
			}
		}
	}


	/**
	 * 设备详细    导航tab切换
	 */
	tableDataTab1: any = [];
	tableDataTab2: any = [];
	tableDataTab2_1: any = [];
	tableDataTab3: any = [];
	tableDataTab4_1: any = [];
	tableDataTab4_2: any = [];
	tableDataTab5: any = [];
	tableDataTab6: any = [];
	totalCountTab: number = 0;
	pageSizeTab: number = 10;
	curPageTab: number = 1; //分页当前页
	activeTab: string = '';
	btnGroupActive: string = '5';//快捷时间按钮(默认三个月);
	btnGroupActiveText: string = '近三个月';//快捷时间按钮文字
	startDateBtn: string = '';
	endDateBtn: string = '';
	/**
	 * 时间快捷选择方式:一周/半个月/一个月/两个月/三个月
	 */
	selectTimeFast(val) {
		this.btnGroupActive = val;
		let temDate = new Date();
		switch (val) {
			case '1':
				this.btnGroupActiveText = '近一周';
				temDate.setDate(temDate.getDate() - 7);//近一周
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			//			case '2':
			//				this.btnGroupActiveText = '近半个月';
			//				temDate.setDate(temDate.getDate() - 15);//近半个月
			//				this.startDateBtn = common.getTimeMmss(temDate);
			//				this.endDateBtn = common.getNowTime();
			//				break;
			case '3':
				this.btnGroupActiveText = '近一个月';
				temDate.setMonth(temDate.getMonth() - 1);//近一个月
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			//			case '4':
			//				this.btnGroupActiveText = '近两个月';
			//				temDate.setDate(temDate.getMonth() - 2);//近两个月
			//				this.startDateBtn = common.getTimeMmss(temDate);
			//				this.endDateBtn = common.getNowTime();
			//				break;
			case '5':
				this.btnGroupActiveText = '近三个月';
				temDate.setMonth(temDate.getMonth() - 3);//近三个月
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			case '6':
				this.btnGroupActiveText = '近半年';
				temDate.setMonth(temDate.getMonth() - 6);//近半年
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			case '7':
				this.btnGroupActiveText = '全部';
				// temDate.setFullYear(temDate.getFullYear() - 1);//近一年
				this.startDateBtn = '2017-01-01 00:00:00';
				this.endDateBtn = common.getNowTime();
				break;
			default:
				this.btnGroupActive = '5';
				this.btnGroupActiveText = '近三个月';
				temDate.setDate(temDate.getDate() - 90);//默认近三个月
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
		}
		this.getDeviceInfoData();
		this.getTableDataTab(this.activeTab);
	}
	getTabData(type) {
		this.tableDataTab1 = [];
		this.tableDataTab2 = [];
		this.tableDataTab2_1 = [];
		this.tableDataTab3 = [];
		this.tableDataTab3 = [];
		this.tableDataTab4_1 = [];
		this.tableDataTab4_2 = [];
		this.tableDataTab5 = [];
		this.tableDataTab6 = [];
		this.totalCountTab = 0;
		this.pageSizeTab = 10;
		this.curPageTab = 1;
		this.activeTab = type;
		if (this.btnGroupActive == '5') {
			let temDate = new Date();
			temDate.setDate(temDate.getDate() - 90);//默认近三个月
			this.startDateBtn = common.getTimeMmss(temDate);
			this.endDateBtn = common.getNowTime();
		}
		this.getTableDataTab(type);
	}
	//获取数据:故障信息/维修信息/警报信息/数据修复/固件升级/系数设置
	getTableDataTab(type) {
		let reqData: any, param: any;
		switch (type) {
			case '':
				this.getDeviceInfoData();
				break;
			case '1':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						carNumber: this.selectRowData.carNumber,
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('dataExceptionRecord/dataRecordPage.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					for (let item of result.exhibitDatas) {
						item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);
						item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
						item.exceptionType = this.getExceptionTypeName(item.exceptionType);
						item.programType = this.getProgramTypeName(item.programType);
						if (item.coefficient) {
							let coefArr = [];
							for (let i = 0; i < item.coefficient.length; i++) {
								let _item = item.coefficient[i];
								if (_item && _item != '0') {
									var obj = {
										value: item.coefficient[i],
										index: i + 1
									}
									coefArr.push(obj);
								}
							}
							item.coef = coefArr;
						} else {
							item.coef = [];
						}
					}
					this.tableDataTab1 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '2':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						searchKey: this.selectRowData.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('fixdatalog/logforpage.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab2 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '2_1':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						searchKey: this.selectRowData.deviceId,
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
						status: "0",
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('exceptionOrderForHaiLuo/findExceptionOrderList.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab2_1 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '3':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('alertlog/deviceShutDownAlarm.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					for (let item of result.exhibitDatas) {
						item.totalSecond = common.secondToDate(item.totalSecond);
					}
					this.tableDataTab3 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '4_1':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						repairedStatus: '0',
						dateType: '1',
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('deviceRepaired/findDeviceRepairedList.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab4_1 = result.exhibitDatas || [];
					this.tableDataTab4_1.map(item => item.callDuration = common.secondToDate(item.callDuration));
					this.totalCountTab = result.recordCount;
				})
				break;
			case '4_2':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						sortType: '2',
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('deviceRepairedV2/findDeviceRepairedV2List.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab4_2 = result.exhibitDatas || [];
					for (let item of this.tableDataTab4_2) {
						var faultPhenomenonList = item.faultPhenomenonList && Array.from(new Set(item.faultPhenomenonList));
						item.faultPhenomenonList = faultPhenomenonList.length > 0 ? faultPhenomenonList.join(",") : '';

						var repairContentList = item.repairContentList && Array.from(new Set(item.repairContentList));
						item.repairContentList = repairContentList.length > 0 ? repairContentList.join(",") : '';

						var repairSubdivideList = item.repairSubdivideList && Array.from(new Set(item.repairSubdivideList));
						item.repairSubdivideList = repairSubdivideList.length > 0 ? repairSubdivideList.join(",") : '';

						item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
					}
					this.totalCountTab = result.recordCount;
					this.repairedDeviceInfo.fixedCount = result.recordCount;
				})
				break;
			case '5':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('log/upgrade.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab5 = result.exhibitDatas || [];
					this.totalCountTab = result.recordCount;
				})
				break;
			case '6':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('deviceCoefLog/deviceCoefLogforpage.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					for (let item of result.exhibitDatas) {
						if (item.newCoef) {
							let newCoef = [];
							for (let i = 0; i < item.newCoef.length; i++) {
								let _item = item.newCoef[i];
								if (_item) {
									let obj: any = {
										value: item.newCoef[i],
										index: i + 1
									}
									newCoef.push(obj);
								}
							}
							item.newCoef = newCoef;
						} else {
							item.newCoef = [];
						}

						if (item.oldCoef) {
							let oldCoef = [];
							for (let i = 0; i < item.oldCoef.length; i++) {
								let _item = item.oldCoef[i];
								if (_item) {
									let obj: any = {
										value: item.oldCoef[i],
										index: i + 1
									}
									oldCoef.push(obj);
								}
							}
							item.oldCoef = oldCoef;
						} else {
							item.oldCoef = [];
						}

					}
					this.tableDataTab6 = result.exhibitDatas || [];
					this.totalCountTab = result.recordCount;
				})
				break;
			default:
				this.getDeviceInfoData();
				break;

		}
	}
	refreshTab() {
		this.getTabData(this.activeTab);
	}
	//分页回调
	paginateTab(e) {
		this.curPageTab = e.page + 1;
		this.pageSizeTab = e.rows;
		this.getTableDataTab(this.activeTab);
	}
	//问题分类
	getExceptionTypeName(key) {
		if (key) {
			return this.questionNameList[key];
		} else {
			return '';
		}
	}
	//现象分类
	getProgramTypeName(key) {
		if (key) {
			return this.questionDeatailNameList[key];
		} else {
			return '';
		}
	}
	questionNameList: any = {
		'1': '算法问题',
		'2': '硬件问题',
		'3': '司机问题',
		'4': '对接问题',
		'5': '运维问题',
		'6': '安装问题'
	};
	questionDeatailNameList: any = {
		'100': '其他',
		'101': '上货问题',
		'102': '卸货问题',
		'103': '在途问题',
		'104': '多次上货',
		'105': '多次卸货',
		'200': '其他',
		'201': '主机问题',
		'202': '传感器问题',
		'203': 'GPS问题',
		'204': '线材问题',
		'300': '其他',
		'301': '司机问题',
		'400': '其他',
		'401': '对接问题',
		'500': '其他',
		'501': '运维问题',
		'601': '安装问题',
		'600': '其他'
	}
	/**
	 * 设备详细(设备基本信息/故障信息/维修信息/警报信息/数据修复)
	 */
	selectRowData: any = {};//选中数据查看的数据row
	deviceDetail(row, modal) {
		if (row == 'btn') {
			this.checkSelectedRow('请选择一条数据进行查看');
			if (!this.selectedRow) {
				return;
			} else {
				this.selectRowData = this.selected[0];
			}
		} else {
			this.selectRowData = row;
		}
		if (this.isShowFirmwareInfo || this.isShowAlarmInfo || this.isShowDataInfo || this.isShowRepairInfo || this.isShowDeviceInfo) {
			// $('#deviceDetailModal').modal('show');
			modal.show()
			$('.s-lis').removeClass('active');
			$('.tab-pane').removeClass('active');
			// $('.s-lis').eq(0).addClass('active');
			// $('.s-lis').eq(0).find('a').attr('aria-expanded', 'true');
			// console.log($('.s-lis'))
			if(this.isShowDeviceInfo){
				this.getTabData('')
				$('.all').eq(0).addClass('active');
				$('.all').eq(0).find('a').attr('aria-expanded', 'true');
				$('#all').eq(0).addClass('active');
			}else if(this.isShowRepairInfo){
				this.getTabData('4_1')
				$('.waitRepaired').eq(0).addClass('active');
				$('.waitRepaired').eq(0).find('a').attr('aria-expanded', 'true');
				$('#waitRepaired').eq(0).addClass('active');
			}else if(this.isShowDataInfo){
				this.getTabData('1')
				$('.question').eq(0).addClass('active');
				$('.question').eq(0).find('a').attr('aria-expanded', 'true');
				$('#question').eq(0).addClass('active');
			}else if(this.isShowAlarmInfo){
				this.getTabData('3')
				$('.lis-alert').eq(0).addClass('active');
				$('.lis-alert').eq(0).find('a').attr('aria-expanded', 'true');
				$('#alert').eq(0).addClass('active');
			}else if(this.isShowFirmwareInfo){
				this.getTabData('5')
				$('.version').eq(0).addClass('active');
				$('.version').eq(0).find('a').attr('aria-expanded', 'true');
				$('#version').eq(0).addClass('active');
			}
			
			this.btnGroupActive = '5'
			let temDate = new Date();
			temDate.setDate(temDate.getDate() - 90);//默认近三个月
			this.startDateBtn = common.getTimeMmss(temDate);
			this.endDateBtn = common.getNowTime();
			this.getDeviceInfoData();
		}else{
			this.jsonApiService.message('设备详情里面的tab标签权限未开放');
		}
	}
	/**
	 * 关闭设备详情弹窗
	 */
	cancelDeviceDetail(modal) {
		// $('#deviceDetailModal').modal('hide');
		modal.hide();
	}
	/**
	 * 获取设备信息 (设备基本信息/故障信息/维修信息/警报信息/数据修复)
	 */
	deviceBaseInfo: any = {
		companyName: '',
		carNumber: '',
		deviceId: '',
		hwVersion: '',
		useTypeL1: '',
		useTypeL2: '',
		userTypeName: '',
		sensorType: '',
		productNo: '',
		iccid: '',
		driverName: '',
		phone: '',
		inputDate: '',
		userNameForCreate: '',
		sensorChannel: [],
		coef: [],
		coefT: [],
		version: ''
	};
	questionRecordInfo: any = [];//问题记录
	questionRecordTotal: number = 0;//问题记录总和
	dataFixInfo: any = {};//数据修复
	alertDataInfo: any = {};//警报数据
	repairedDeviceInfo: any = {};//维修记录
	deviceRealTimeDataInfo: any = {};//设备实时数据
	isShowGPSAlert: boolean = false;//是否显示GPS数据更新异常警报提示
	isShowOfflineAlert: boolean = false;//是否显示离线警报提示
	offlineDiffTime: string = '';//离线时长
	weightCount: number = 0;//过磅次数
	initDeviceBaseInfo() {
		this.deviceBaseInfo = {
			companyName: '',
			carNumber: '',
			deviceId: '',
			hwVersion: '',
			useTypeL1: '',
			useTypeL2: '',
			userTypeName: '',
			sensorType: '',
			productNo: '',
			iccid: '',
			driverName: '',
			phone: '',
			inputDate: '',
			userNameForCreate: '',
			sensorChannel: [],
			coef: [],
			coefT: [],
			version: ''
		};
		this.isShowGPSAlert = false;
		this.isShowOfflineAlert = false;
		this.questionRecordInfo = [];
		this.dataFixInfo = {};
		this.alertDataInfo = {};
		this.repairedDeviceInfo = {};
		this.deviceRealTimeDataInfo = {};
		this.offlineDiffTime = '';
		this.weightCount = 0;
	}
	getDeviceInfoData() {
		this.initDeviceBaseInfo();
		//设备基本信息
		this.jsonApiService.http_obj("system/getDeviceBaseInfoByDeviceId.html", { deviceId: this.selectRowData.deviceId }).subscribe(data => {
			if (data.success && data.data) {
				for (let item in this.deviceBaseInfo) {
					if (item === 'coef' || item === 'coefT' || item === 'sensorChannel') {
						this.deviceBaseInfo[item] = data.data[item] || [];
					} else {
						this.deviceBaseInfo[item] = data.data[item] || '';
					}
				}
				this.deviceBaseInfo.userTypeName = this.getUseTypeNameL2(this.deviceBaseInfo.useTypeL2);
				if (this.deviceBaseInfo.coef) {
					let coefArr = [];
					for (let i = 0; i < this.deviceBaseInfo.coef.length; i++) {
						let _item = this.deviceBaseInfo.coef[i];
						if (_item) {
							let obj: any = {
								value: _item,
								index: i + 1
							}
							coefArr.push(obj);
						}
					}
					this.deviceBaseInfo.coefT = coefArr;
				} else {
					this.deviceBaseInfo.coefT = [];
				}
			}

		})
		//问题统计(近三个月)
		this.jsonApiService.http_obj("system/countDeviceDataRecordByDeviceId.html", { deviceId: this.selectRowData.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.questionRecordTotal = 0;
				this.questionRecordInfo = data.data;
				for (let item of this.questionRecordInfo) {
					this.questionRecordTotal += +item.reasonCount;
				}
			}
		})
		//数据修复统计(近三个月)
		this.jsonApiService.http_obj("system/queryDataFixCountByDeviceId.html", { deviceId: this.selectRowData.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.dataFixInfo = data.data;
			}
		})
		//警报统计(近三个月)
		this.jsonApiService.http_obj("system/queryAlarmCountByDeviceId.html", { deviceId: this.selectRowData.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.alertDataInfo = data.data;
			}
		})
		//维修记录统计(近三个月)
		this.jsonApiService.http_obj("system/queryDeviceRepairedByDeviceId.html", { deviceId: this.selectRowData.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.repairedDeviceInfo = data.data;
			}
		})
		//设备状态(实时数据)
		let deviceId = this.selectRowData.deviceId;
		this.jsonApiService.http_obj("system/getRealTimeData.html", { deviceId: this.selectRowData.deviceId }).subscribe(data => {
			if (data.success && data.data) {
				this.deviceRealTimeDataInfo = data.data;
				let carUploadDate, gpsUploadDate;
				if (this.deviceRealTimeDataInfo.carUploadDate) {
					carUploadDate = this.deviceRealTimeDataInfo.carUploadDate;
				}
				if (this.deviceRealTimeDataInfo.gpsUploadDate) {
					gpsUploadDate = this.deviceRealTimeDataInfo.gpsUploadDate;
				}
				if (gpsUploadDate && carUploadDate) {
					let abs = Math.abs(common.mmsstoTimestamp(carUploadDate) - common.mmsstoTimestamp(gpsUploadDate));
					abs >= 30 * 60 * 1000 ? this.isShowGPSAlert = true : this.isShowGPSAlert = false; //计算GPS是否异常:更新时间 - gps更新时间  > 30分钟    =>GPS异常
					this.getWeighbridge(deviceId);
				}
			}
		})
	}
	//获取磅单数据:用于判断离线异常
	getWeighbridge(deviceId) {
		this.jsonApiService.http_obj("weighbridge/weightforreal.html", { deviceId: deviceId, startTime: this.deviceRealTimeDataInfo.updateTime, endTime: common.getNowTime() }).subscribe(data => {
			if (data.success && data.data) {
				this.weightCount = 0;
				let diffTiem = common.mmsstoTimestamp(common.getNowTime()) - common.mmsstoTimestamp(this.deviceRealTimeDataInfo.updateTime);
				this.offlineDiffTime = common.secondToDate(diffTiem / 1000);//计算离线时长:当前时间 - 最后更新时间
				let weightData = data.data;
				for (let item of weightData) {
					if (+item.weight > 0) {
						this.isShowOfflineAlert = true;
						this.weightCount += 1;//计算榜单数
					}
				}
			}
		})
	}
	/**
	 * 问题记录跳转
	 */
	jumpQuestionByHand(type1, type2, value) {
		if (value == 0) { this.jsonApiService.message('无记录!'); return };
		$('#deviceDetailModal').modal('hide');
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			exceptionType: type1,
			programType: type2
		}
		this.router.navigate(['/abnormal-alert/artificialMonitor']);
		common.setCookie('jumpQuestionByHandList', JSON.stringify(queryParams));
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)
	}
	/**
	 * 设备警报跳转
	 */
	jumpAlertDataList(type, value) {
		if (!value) { this.jsonApiService.message('无记录!'); return };
		$('#deviceDetailModal').modal('hide');
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			type: type,
		}
		this.router.navigate(['/abnormal-alert/device-off']);
		common.setCookie('jumpAlertDataList', JSON.stringify(queryParams));
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)
	}
	/**
	 * 设备维修跳转
	 */
	jumpRepairedDeviceList(type, dateType, value) {
		if (!value) { this.jsonApiService.message('无记录!'); return };
		$('#deviceDetailModal').modal('hide');
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			repairedStatus: type,
			dateType: dateType,
		}
		if (type == '0') {
			this.router.navigate(['/device-management/fault']);
		} else if (type == '1') {
			this.router.navigate(['/device-management/faultV2']);
		}
		common.setCookie('jumpRepairedDeviceList', JSON.stringify(queryParams));
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)
	}
	jumpDataFixList(type, value) {
		if (!value) { this.jsonApiService.message('无记录!'); return };
		$('#deviceDetailModal').modal('hide');
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			type: null
		}
		switch (type) {
			case '1':
				queryParams.type = '1';
				this.router.navigate(['/log-info/repairRecord']);
				common.setCookie('jumpDataFixList', JSON.stringify(queryParams));
				break;
			case '2':
				queryParams.type = '2';
				this.router.navigate(['/log-info/repairRecord']);
				common.setCookie('jumpDataFixList', JSON.stringify(queryParams));
				break;
			case '3':
				queryParams.type = '0';
				this.router.navigate(['/abnormal-alert/order']);
				common.setCookie('jumpExceptionOrderList', JSON.stringify(queryParams));
				break;
			default:
				break;
		}
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)

	}




	/**
	 * 参数配置
	 */
	config: any = {//参数配置
		deviceId: '',
		weight: '',
		upload: '',
		binVersion: '',//固件版本
		algorithmVersion: '',//算法版本
		bootLoaderVersion: '',
		longitude: '',
		latitude: '',
		speed: '',
		azimuth: '',//方位角
		satellites: '',//卫星数
		GPSstrength: '',//GPS信号强度
	};
	//关闭参数配置弹窗
	cancelparamConfig(val) {
		val.hide();
		for (var item in this.config) {
			if (item === 'params') {
				for (var lis in this.config.params) {
					this.config.params[lis] = '';
				}
			} else {
				this.config[item] = '';
			}
		}
	}
	//读取上传频率
	outputUpload() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=2';
		this.jsonApiService.http2("devicemanage/sendCodeForReadTimePeriod.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.config.upload = data.data;
			}
		})
	}
	//写上传频率
	inputUpload() {
		if (parseInt(this.config.upload) == 0) {
			this.jsonApiService.message('上传频率范围是大于0小于或等于60');
			return;
		}

		if (!this.config.upload) {
			this.jsonApiService.message('上传频率不能为空');
			return;
		}
		if (!(/(^[1-9]\d*$)/.test(this.config.upload))) {
			this.jsonApiService.message('上传频率必须为正整数类型');
			return;
		}

		if (parseInt(this.config.upload) == 0 || parseInt(this.config.upload) > 60 || parseInt(this.config.upload) < 0) {
			this.jsonApiService.message('上传频率范围是大于0小于或等于60');
			return;
		}
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=2&time=' + this.config.upload;
		this.jsonApiService.http2("devicemanage/sendCodeForWriteTimePeriod.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
		})
	}
	//读取设备版本
	outputDeviceVersion() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=2';
		this.jsonApiService.http2("devicemanage/sendCodeForReadDeviceVersion.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				let temData = data.data.split(',');
				if (temData) {
					this.config.binVersion = temData[0] ? temData[0] : '';
					this.config.algorithmVersion = temData[1] ? temData[1] : '';
					this.config.bootLoaderVersion = temData[2] ? temData[2] : '';
				}
			}
		})
	}
	//读取GPS
	outputGPS() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=2';
		this.jsonApiService.http2("devicemanage/sendCodeForReadGps.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				let temData = data.data.split(',');
				if (temData) {
					this.config.longitude = temData[0] ? temData[0] : '';
					this.config.latitude = temData[1] ? temData[1] : '';
					this.config.speed = temData[2] ? temData[2] : '';
					this.config.azimuth = temData[3] ? temData[3] : '';
					this.config.satellites = temData[4] ? temData[4] : '';
					this.config.GPSstrength = temData[5] ? temData[5] : '';
				}
			}
		})
	}
	//参数配置
	paramConfig(val) {
		this.selectedRow = false;
		this.checkSelectedRow('请选择一条数据进行参数配置');
		if (this.selectedRow) {
			this.config.upload = ''
			val.show();
		}
	}

	/**
	 * 待维修的删除
	 */
	deleteRepaireRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			var reqdata = "id=" + row.id;
			this.jsonApiService.http('deviceRepaired/delDeviceRepairedById.html', reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
				this.getTabData('4_1');
			})
		})
	}


	// 数据导出
	exportData() {
		let params = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				searchKey: this.searchKey,
				company: this.selectedCompanyId,
				online: this.online,
				state: this.state,
				sort: this.sortType,
				useTypeL2: $('#TcarTypeSelect2').val(),
				useTypeL1: $('#TcarTypeSelect2').val().slice(0, 2)
			},
			isExport: true
		}
		common.exprotDataFile(params, 'gridPager', config.BaseURL + 'system/realTimeDataByAuth.html')
	}
}